<template>
  <div class="app-container">
    <el-card>
      <el-button
          type="primary"
          icon="plus"
          @click="handleAdd(0)"
          v-hasPermi="['product:category:add']"
          style="margin-bottom: 15px"
      >
        新增一级分类
      </el-button>

      <!-- 树形表格 -->
      <el-table
          :data="categoryList"
          row-key="categoryId"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          default-expand-all
          style="width: 100%"
      >
        <el-table-column prop="name" label="分类名称" width="300">
          <template #default="{ row, $index }">
            <span
                :style="{
                paddingLeft: (row.level - 1) * 20 + 'px',
                display: 'inline-block',
                minWidth: '120px'
              }"
            >
              {{ row.name }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="分类图标" width="150" align="center">
          <template #default="{ row }">
            <el-image
                :src="row.image"
                :preview-src-list="[row.image]"
                fit="cover"
                style="width: 100px; cursor: pointer"
            />
          </template>
        </el-table-column>

        <el-table-column prop="sort" label="排序" align="center" />

        <el-table-column prop="status" label="状态"  align="center">
          <template #default="{ row }">
            <el-tag v-if="row.status === '0'" type="success" >启用</el-tag>
            <el-tag v-else type="info" >禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template #default="{ row }">
            {{ parseTime(row.createTime) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="220" align="center">
          <template #default="{ row }">
            <el-button
                v-if="row.level < 3"
                type="text"
                @click="handleAdd(row.categoryId)"
                v-hasPermi="['product:category:add']"
            >
              新增子级
            </el-button>
            <el-button
                type="text"
                @click="handleUpdate(row)"
                v-hasPermi="['product:category:edit']"
            >
              编辑
            </el-button>
            <el-button
                type="text"
                style="color: #f56c6c"
                @click="handleDelete(row)"
                v-hasPermi="['product:category:remove']"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!--分页组件-->
    <pagination
        v-show="total > 0"
        :total="total"
        :page-sizes="[2, 5, 10, 20]"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 表单弹窗 -->
    <el-dialog :title="title" v-model="open" width="500px" @close="cancel">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="父级分类">
          {{ form.parentName || '无（一级分类）' }}
        </el-form-item>
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="图片" prop="imageUrl">
          <ImageUpload v-model="form.image" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" :max="999" controls-position="right" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="0">启用</el-radio>
            <el-radio label="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, getCurrentInstance } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { listCategory, addCategory, updateCategory, delCategory } from '@/api/product/category'
import ImageUpload from "@/components/ImageUpload/index.vue";
import {parseTime} from "@/utils/ruoyi.js";

const { proxy } = getCurrentInstance()
const categoryList = ref([])
const open = ref(false)
const title = ref('')
const isEdit = ref(false)
const total = ref(0)
const form = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10
  },
  categoryId: null,
  name: '',
  parentId: 0,
  parentName: '',
  sort: 0,
  status: '0',
  image: ''
})
const {queryParams} = toRefs(form)

const rules = {
  name: [{ required: true, message: '分类名称不能为空', trigger: 'blur' }],
  sort: [{ required: true, message: '排序不能为空', trigger: 'blur' }]
}

// 查询列表
const getList = () => {
  listCategory(queryParams.value).then((response) => {
    categoryList.value = response.rows || []
    total.value = response.total || 0;
  })
}

// 新增
const handleAdd = (parentId) => {
  isEdit.value = false
  form.parentId = parentId
  form.categoryId = null
  form.parentName = parentId === 0 ? '无（一级分类）' : getCategoryName(parentId)
  form.name = ''
  form.sort = 0
  form.status = '0'
  form.image = ''
  title.value = '添加分类'
  open.value = true
}

// 获取分类名称
const getCategoryName = (id) => {
  const find = (list, id) => {
    for (const item of list) {
      if (item.categoryId === id) return item.name
      if (item.children?.length) {
        const found = find(item.children, id)
        if (found) return found
      }
    }
    return ''
  }
  return find(categoryList.value, id)
}

// 编辑
const handleUpdate = (row) => {
  isEdit.value = true
  form.parentId = row.parentId
  form.parentName = row.parentId === 0 ? '无（一级分类）' : getCategoryName(row.parentId)
  form.categoryId = row.categoryId
  form.name = row.name
  form.sort = row.sort
  form.status = row.status
  form.image = row.image
  title.value = '修改分类'
  open.value = true
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm(
      `是否确认删除分类 "${row.name}" 及其所有子分类？`,
      '警告',
      { type: 'warning' }
  ).then(() => {
    delCategory(row.categoryId).then(() => {
      ElMessage.success('删除成功')
      getList()
    })
  })
}

// 提交
const submitForm = () => {
  proxy.$refs.formRef.validate((valid) => {
    if (valid) {
      if (isEdit.value) {
        updateCategory(form).then(() => {
          ElMessage.success('修改成功')
          open.value = false
          getList()
        })
      } else {
        const submitData = { ...form }
        addCategory(submitData).then(() => {
          ElMessage.success('新增成功')
          open.value = false
          getList()
        })
      }
    }
  })
}

// 取消
const cancel = () => {
  open.value = false
  proxy.$refs.formRef.resetFields()
}

// 初始化
getList()
</script>

<style scoped>
:deep(.el-table) {
  font-size: 14px;
}
</style>